<template>
  <div class="home-container">
    <div class="header-container">
      <div class="left-container">
        <div class="item-container">
          <p class="item-label">状态:</p>
          <el-select v-model="searchParams.status" placeholder="Select" style="width: 140px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="item-container">
          <p class="item-label">渠道:</p>
          <el-select v-model="searchParams.channel" placeholder="Select" style="width: 140px">
            <el-option v-for="item in channerOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="item-container">
          <p class="item-label">MD5:</p>
          <el-input v-model="searchParams.md5" maxlength="32" placeholder="请输入MD5值" show-word-limit type="text" />
        </div>
        <el-button type="success" @click="getManageList" style="margin-bottom: 10px;">
          <el-icon style="margin-right: 10px;">
            <Search />
          </el-icon>
          搜索
        </el-button>
      </div>
      <div class="right-container" v-if="currentPageData?.showAddButton">
        <el-button type="primary" @click="handleData(HANDLE_TYPE_ENUM.TYPE_ADD)" style="margin-bottom: 10px;">
          <el-icon style="margin-right: 10px;">
            <Plus />
          </el-icon>
          新增
        </el-button>
      </div>
    </div>
    <el-table :data="tableData" :border="true" style="width: 100%;min-height: 200px;flex:1;"
      v-loading="tableLoading">
      <el-table-column v-for="item in tableShowKey" :prop="item.key" :label="item.title" :min-width="item.width" :key="item.key">
        <template #default="scope" v-if="item.key === 'name'">
          <div>
            <el-button link type="primary" size="small" @click="openDetailDialog(scope.row)">{{ scope.row[item.key] }}</el-button>
          </div>
        </template>
        <template #default="scope" v-else-if="['md5', 'url', 'rtaurl', 'mlink'].includes(item.key)">
          <el-popover v-if="scope.row[item.key]" effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div> {{ scope.row[item.key] }}</div>
            </template>
            <template #reference>
              <div v-if="scope.row[item.key]">
                <div class="overflow-hidden">{{ scope.row[item.key] }}</div>
                <div class="col-container">
                  <el-button type="primary" size="small" @click="copyRight(scope.row[item.key])">复制</el-button>
                </div>
              </div>
            </template>
          </el-popover>
        </template>
        <template #default="scope" v-else-if="item.key === 'status'">
          <div v-if="`${scope.row[item.key]}`">
            {{ statusOptions.filter(v => v.value === scope.row[item.key])[0]?.label }}
          </div>
        </template>
        <template #default="scope" v-else-if="item.key === 'pkgtype'">
          <div v-if="`${scope.row[item.key]}`">
            {{ pkgtypeOptions.filter(v => String(v.value) === String(scope.row[item.key]))[0]?.label }}
          </div>
        </template>
        <template #default="scope" v-else-if="item.key === 'tagid'">
          <div v-if="scope.row[item.key]">
            <el-tag v-for="item in scope.row[item.key]?.split(',')" :key="item"> {{ item }}</el-tag>
          </div>
        </template>
        <template #default="scope" v-else-if="item.key === 'btime'">
          <div>
            {{ showPublistTime(scope.row) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="110" align="center">
        <template #default="scope">
          <el-button type="primary" @click="handleData(HANDLE_TYPE_ENUM.TYPE_UPDATE, scope.row)">更新</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination-container" v-model:current-page="searchParams.page"
      v-model:page-size="searchParams.size" :page-sizes="[10, 20, 30, 40]" :background="true"
      layout=" prev, pager, next, jumper, ->, sizes,total" :total="total" @current-change="getManageList"
      @size-change="getManageList" />
    <HandlerDialog ref="HandlerDialogRef" :handleType="handleType" :originData="originData.data"
      @on-handler-completed="getManageList" v-if="pageType === PAGE_TYPE_ENUM.TYPE_APP_1"/>
    <HandlerDialogV2 ref="HandlerDialogRef" :handleType="handleType" :originData="originData.data"
      @on-handler-completed="getManageList" :showFormKey="currentPageData?.tableListShowKey || null" v-else/>
    <DetailDialog ref="DetailDialogRef" :appid="currentAppid" :pageType="pageType"/>
  </div>
</template>
  
<script setup lang='ts'>
import { ref, onMounted, reactive } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import useClipboard from 'vue-clipboard3'
import HandlerDialog from './components/HandlerDialog.vue'
import HandlerDialogV2 from './components/HandlerDialogV2.vue'
import DetailDialog from './components/DetailDialog.vue'

import { divisionHundred } from '../../utils/index'
import { reqManagelist } from '@/api/home/index.ts'
import type { ISearchParams, IListItemData, ISelectOptionsType, ITableShowKey, IPageMapData } from '@/types/home/type.ts'
import { StatusOptions, PkgtypeOptions, ChannerOptions, HANDLE_TYPE_ENUM, PAGE_TYPE_ENUM, HomeTableListShowKey } from '@/types/home/constData.ts'
import { PageData } from './config/PageMapData'
import { isEmptyFillLine } from '../../utils/index'

const props = defineProps<{
  pageType: PAGE_TYPE_ENUM
}>()
// 使用插件
const { toClipboard } = useClipboard()
const statusOptions = ref<ISelectOptionsType[]>(StatusOptions)
const channerOptions = ref<ISelectOptionsType[]>(ChannerOptions)
// @ts-ignore
const pkgtypeOptions = ref<ISelectOptionsType[]>(PkgtypeOptions)
const HandlerDialogRef = ref()
const DetailDialogRef = ref()
// 显示具体data数据的appid值 传给组件 用请求数据
const currentAppid = ref<string>('')
const tableLoading = ref<boolean>(false)
// 当前页面的map值
const currentPageData = ref<IPageMapData | undefined>()
// 区别table展示的key值
const tableShowKey = ref<ITableShowKey[]>([])

let handleType = ref<string>(HANDLE_TYPE_ENUM.TYPE_ADD)
let originData = reactive({
  data: {
  }
})
let total = ref<number>(0)
let searchParams = reactive<ISearchParams>({
  page: 1,
  size: 10,
  md5: '',
  channel: '',
  status: -100
})
let tableData = ref<IListItemData[]>([])
onMounted(() => {
  getManageList()
  initTableShowKey()
})

const initTableShowKey = () => {
  currentPageData.value = (PageData.get(props.pageType) as any)
  const indexTableListShowKey: string[] = currentPageData.value?.tableListShowKey || []
  const keyArr: ITableShowKey[] = []
  HomeTableListShowKey.forEach((item: ITableShowKey) => {
    if (indexTableListShowKey.some((key: string) =>  key.toUpperCase() === item.key.toUpperCase())) {
      keyArr.push({...item})
    }
  })
  tableShowKey.value = keyArr
}

const getManageList = () => {
  tableLoading.value = true
  reqManagelist(searchParams).then(res => {
    const { code, data, msg } = res
    tableLoading.value = false
    if (code === 0) {
      tableData.value = (data.items || []).map((item: IListItemData) => {
        return {
          ...item,
          pkgtype: item.pkgtype === null ? 0 : item.pkgtype,
          bidfloor: divisionHundred(item.bidfloor!),
          budget: divisionHundred(item.budget!),
        }
      })
      total.value = data.totalCount
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
      tableData.value = []
    }
  })
}
const handleData = (type: string, data?: any) => {
  handleType.value = type
  if (data) {
    originData.data = Object.assign(originData.data, data)
  } else {
    originData.data = {
    }
  }
  HandlerDialogRef.value?.handleDialog(true, originData.data)
}

//@ts-ignore
const copyRight = async (msg: string) => {
  try {
    // 复制
    await toClipboard(msg)
    // 复制成功
    ElMessage({
      type: 'success',
      message: '复制成功'
    })
  } catch (e) {
    // 复制失败
    ElMessage({
      type: 'warning',
      message: '复制失败，请稍后重试'
    })
  }
}

const openDetailDialog = (row: any) => {
  currentAppid.value = row.appid
  DetailDialogRef.value?.handleDialog(true)
}
// @ts-ignore
const showPublistTime = (row: any) => {
  return `${isEmptyFillLine(row.btime)}点-${isEmptyFillLine(row.etime)}点`;
}
</script>
  
<style scoped lang="scss">
.home-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .header-container {
    display: flex;
    justify-content: space-between;
    margin: 10px 0;

    .left-container {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      align-items: center;

      .item-container {
        display: flex;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 10px;
        .item-label {
          min-width: 60px;
        }
      }
    }

    .right-container {
      display: flex;
      align-items: center;
    }
  }

  .col-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .overflow-hidden {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  .pagination-container {
    margin: 15px 0;
  }
}</style>